package com.canbot.u05.activity.customvoice;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;

import com.alibaba.fastjson.JSON;
import com.canbot.u05.R;
import com.canbot.u05.activity.BaseActivityNoTitle;
import com.canbot.u05.activity.customvoice.adapter.CustomImageAdapter;
import com.canbot.u05.activity.customvoice.bean.AnswerBean;
import com.canbot.u05.activity.customvoice.bean.CustomImageData;
import com.canbot.u05.activity.customvoice.tool.GridSpacingItemDecoration;
import com.canbot.u05.bean.JsonResponse;
import com.canbot.u05.network.SalesApi;
import com.canbot.u05.socket.IpMsgConst;
import com.canbot.u05.socket.MsgSendUtils;
import com.canbot.u05.socket.MsgType;
import com.canbot.u05.utils.Logger;
import com.canbot.u05.utils.OkHttpUtils;
import com.canbot.u05.utils.PathConst;
import com.canbot.u05.utils.ToastTools;
import com.canbot.u05.widget.LoadingDialogUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by liu.heng  on 2018/5/24.
 * 自定义对话图片选择
 */

public class CustomImageActivity extends BaseActivityNoTitle implements CustomImageAdapter.OnItemClickListener{

        private RecyclerView mRecyclerView;

        private RelativeLayout mRelativeLayout;

        private RelativeLayout remindRelativeLayout;

        private Button next_btn;

        private CustomImageAdapter mCustomImageAdapter;

        private List<CustomImageData> mCustomImageData;

        private final int ADD_IAMGE = 0;

        private final int CHANGE_IMAGE = 1;

        private Dialog dialogLoading;

        private ToastTools toastTools;

        private int currentPosition = -1;

        private int type;

        private int answerType;//回答的方式

        private String answer_text;

        private String question_Str;

        private String picPath = "";

        private static final int TIMEOUT = 100;//超时时间100s

        private AnswerBean mAnswerBean;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_custom_image);
                next_btn = (Button) findViewById(R.id.btn_skip);
                final Intent intent = getIntent();
                type = intent.getIntExtra("type", -1);
                if (type == ADD_IAMGE) {
                        question_Str = intent.getStringExtra("question_Str");
                        answer_text = intent.getStringExtra("answer_Str");
                        answerType = intent.getIntExtra("answerType", 0);
                }
                else {
                        next_btn.setVisibility(View.GONE);
                        question_Str = intent.getStringExtra("question_Str");
                        mAnswerBean = JSON.parseObject(intent.getStringExtra("answer"), AnswerBean.class);
                        picPath = mAnswerBean.getImgpath();
                }
                initView();
        }

        private void initView() {
                mRelativeLayout = (RelativeLayout) findViewById(R.id.my_relativeLayout);
                remindRelativeLayout = (RelativeLayout) findViewById(R.id.remind_relativeLayout);
                mRecyclerView = (RecyclerView) findViewById(R.id.my_gridView);
                getData();

                mCustomImageAdapter = new CustomImageAdapter(this, mCustomImageData,this);
                mRecyclerView.setLayoutManager(new GridLayoutManager(CustomImageActivity.this, 4));  //网格布局，每行为4
                mRecyclerView.addItemDecoration(new GridSpacingItemDecoration(4,52,false));
                mRecyclerView.setAdapter(mCustomImageAdapter);


        }

        @Override
        public void onItemClick(View view) {
                final int i = (int) view.getTag();
                mCustomImageAdapter.setChecked(i);
                mCustomImageAdapter.notifyDataSetChanged();
                currentPosition = i;
        }

        private void getData() {
                mCustomImageData = new ArrayList<>();
                dialogLoading = LoadingDialogUtils.createLoadingDialog(CustomImageActivity.this, getResources().getString(R.string.request));
                dialogLoading.show();
                final String url = "http://" + IpMsgConst.SOCKET_HOST2 + ":7755/";
                final Retrofit retrofit = new Retrofit.Builder()
                        .baseUrl(url)
                        .addConverterFactory(GsonConverterFactory.create())
                        .client(setTimeOut())
                        .build();
                final SalesApi salesApi = retrofit.create(SalesApi.class);
                final Call<JsonResponse> pic = salesApi.getPic("/uupic");
                pic.enqueue(new Callback<JsonResponse>() {
                        @Override
                        public void onResponse(Call<JsonResponse> call, Response<JsonResponse> response) {
                                dialogLoading.dismiss();
                                if (response.body() != null) {
                                        final JsonResponse path = response.body();
                                        Log.e("ChoosePicActivity", response.isSuccessful() + " " + path);
                                        if (path != null) {
                                                if (path.getRc() == -1) {
                                                        return;
                                                }
                                                final List<String> result = JSON.parseArray(path.getResult().toString(), String.class);
                                                Logger.e("ChoosePicActivity", "result==" + result.toString());
                                                for (int i = 0; i < result.size(); i++) {
                                                        final String s = result.get(i);
                                                        Logger.e("ChoosePicActivity", "编辑图片原图片设置选中picPath" + picPath + "------" + s);

                                                        if (picPath != null && picPath.equals(s)) {
                                                                final CustomImageData map = new CustomImageData(s);
                                                                mCustomImageData.add(map);
                                                                mCustomImageAdapter.setChecked(i);
                                                        }
                                                        else {
                                                                final CustomImageData map = new CustomImageData(s);
                                                                mCustomImageData.add(map);
                                                        }
                                                }
                                        }
                                        if (mCustomImageData.size() > 0) {
                                                mCustomImageAdapter.notifyDataSetChanged();
                                        }
                                        else {
                                                remindRelativeLayout.setVisibility(View.VISIBLE);
                                        }
                                }
                        }

                        @Override
                        public void onFailure(Call<JsonResponse> call, Throwable t) {
                                runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                                dialogLoading.dismiss();
                                                ToastTools.newInstance(getApplicationContext()).showText(CustomImageActivity.this.getString(R.string.network_error));
                                        }
                                });
                        }
                });

        }

        /*下一步*/
        public void nextStep(View view) {

                if (currentPosition != -1) {
                        if (type == ADD_IAMGE) {
                                Log.e("imagepath----->", mCustomImageData.get(currentPosition).getImagePath());
                                startActivity(new Intent(this, CustomActionSetActivity.class)
                                        .putExtra("type", 0)
                                        .putExtra("question_Str", question_Str)
                                        .putExtra("answer_Str", answer_text)
                                        .putExtra("answerType", answerType)
                                        .putExtra("image_Path", mCustomImageData.get(currentPosition).getImagePath()));
                                MsgSendUtils.sendStringMsg(MsgType.PLAY_SOUND, PathConst.CUSTOM_DIALOG_PAYH + "u05_dzdz_001.wav");
                                MsgSendUtils.sendStringMsg(MsgType.EYE_MOTION, "14");
                                MsgSendUtils.sendStringMsg(MsgType.ACTION, "14006");
                        }
                        else if (type == CHANGE_IMAGE) {
                                dialogLoading = LoadingDialogUtils.createLoadingDialog(this, getResources().getString(R.string.request));
                                dialogLoading.show();
                                final HashMap<String, Object> hasMap = new HashMap<>();
                                hasMap.put("type", "3");
                                hasMap.put("question", question_Str);
                                hasMap.put("imagepath", mCustomImageData.get(currentPosition).getImagePath());
                                Log.e("----->", question_Str + "&&&&&" + mCustomImageData.get(currentPosition).getImagePath());
                                OkHttpUtils.upLoadFile("http://" + IpMsgConst.SOCKET_HOST2 + ":7755/" + "dialogcustom", hasMap, new OkHttpUtils.OkHttpCallBack() {
                                        @Override
                                        public void onSuccess(String result) {
                                                dialogLoading.dismiss();

                                                final JsonResponse strMsgBean = JSON.parseObject(result, JsonResponse.class);

                                                final String msg;

                                                if (strMsgBean.getRc() != 0) {
                                                        msg = strMsgBean.getMsg();
                                                }
                                                else {
                                                        msg = CustomImageActivity.this.getString(R.string.update_successfully);
                                                }
                                                runOnUiThread(new Runnable() {
                                                        @Override
                                                        public void run() {
                                                                ToastTools.newInstance(getApplicationContext()).showText(msg);
                                                                finish();
                                                        }
                                                });
                                        }

                                        @Override
                                        public void onFailure() {
                                                runOnUiThread(new Runnable() {
                                                        @Override
                                                        public void run() {
                                                                dialogLoading.dismiss();
                                                                ToastTools.newInstance(getApplicationContext()).showText(getString(R.string.network_error));
                                                        }
                                                });
                                        }
                                });
                        }
                }
                else {
                        ToastTools.newInstance(getApplicationContext()).showText(getString(R.string.please_select_picture));
                }
        }

        /*返回*/
        public void back(View view) {
                finish();
        }

        /*跳过*/
        public void newDialogue(View view) {
                if (type == ADD_IAMGE) {
                        startActivity(new Intent(this, CustomActionSetActivity.class)
                                .putExtra("type", 0)
                                .putExtra("question_Str", question_Str)
                                .putExtra("answer_Str", answer_text)
                                .putExtra("answerType", answerType)
                                .putExtra("image_Path", ""));
                        finish();
                        MsgSendUtils.sendStringMsg(MsgType.PLAY_SOUND, PathConst.CUSTOM_DIALOG_PAYH + "u05_dzdz_001.wav");
                        MsgSendUtils.sendStringMsg(MsgType.EYE_MOTION, "14");
                        MsgSendUtils.sendStringMsg(MsgType.ACTION, "14006");
                }
                else if (type == CHANGE_IMAGE) {
                        finish();
                }
        }

        /**
         * 设置超时
         *
         * @return
         */
        private OkHttpClient setTimeOut() {
                final OkHttpClient client = new OkHttpClient.Builder()
                        .connectTimeout(TIMEOUT, TimeUnit.SECONDS)
                        .writeTimeout(TIMEOUT, TimeUnit.SECONDS)
                        .readTimeout(TIMEOUT, TimeUnit.SECONDS)
                        .build();
                return client;

        }

        @Override
        protected void onDestroy() {
                // TODO Auto-generated method stub
                if (dialogLoading != null && dialogLoading.isShowing()) {
                        dialogLoading.dismiss();
                        dialogLoading = null;
                }
                super.onDestroy();
        }
}
